package com.skyolder.milkbee.web.rest.my;

import java.net.URI;
import java.net.URISyntaxException;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.codahale.metrics.annotation.Timed;
import com.skyolder.milkbee.domain.Candidate;
import com.skyolder.milkbee.domain.Leaguer;
import com.skyolder.milkbee.domain.Questionnaire;
import com.skyolder.milkbee.domain.User;
import com.skyolder.milkbee.dto.Vote;
import com.skyolder.milkbee.security.SecurityUtils;
import com.skyolder.milkbee.service.CandidateService;
import com.skyolder.milkbee.service.LeaguerService;
import com.skyolder.milkbee.service.QuestionnaireService;
import com.skyolder.milkbee.service.UserService;
import com.skyolder.milkbee.web.rest.util.HeaderUtil;
import com.skyolder.milkbee.web.rest.util.PaginationUtil;

import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api/my")
public class MyVoteResource {

	private final Logger log = LoggerFactory.getLogger(MyVoteResource.class);

	@Inject
	private QuestionnaireService questionnaireService;
	@Inject
	private CandidateService candidateService;
	@Inject
	private UserService userService;
	@Inject
	private LeaguerService leaguerService;

	@PostMapping("/votes")
	@Timed
	public ResponseEntity<Vote> createQuestionnaire(@RequestBody Vote vote) throws URISyntaxException {
		log.debug("REST request to save Vote : {}", vote);
		if (vote.getQuestionnaire().getId() != null) {
			return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("questionnaire", "idexists",
					"A new questionnaire cannot already have an ID")).body(null);
		}
		Optional<User> ouser = userService.getUserWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin());
		Leaguer leaguer=leaguerService.findByUser(ouser.get());
		vote.getQuestionnaire().setUserId(ouser.get().getId());
		vote.getQuestionnaire().setLeaguerId(leaguer.getId());
		vote.getQuestionnaire().setCreatedAt(ZonedDateTime.now());
		Questionnaire result = questionnaireService.save(vote.getQuestionnaire());
		for (Candidate c : vote.getCandidates()) {
			c.setQuestionnaireId(result.getId());
			c = candidateService.save(c);
		}
		vote.setQuestionnaire(result);
		return ResponseEntity.created(new URI("/api/questionnaires/" + vote.getId()))
				.headers(HeaderUtil.createEntityCreationAlert("questionnaire", vote.getId().toString())).body(vote);
	}

	@GetMapping("/votes")
	@Timed
	public ResponseEntity<List<Vote>> getAllMyVote(@ApiParam Pageable pageable) throws URISyntaxException {
		log.debug("REST request to get a page of Questionnaires");
		Optional<User> ouser = userService.getUserWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin());
		Page<Questionnaire> page = questionnaireService.findByUserId(ouser.get().getId(), pageable);
		List<Long> ids = new ArrayList<Long>();
		List<Vote> votes = new ArrayList<Vote>();
		for (Questionnaire questionnaire : page.getContent()) {
			ids.add(questionnaire.getId());
			Vote vote = new Vote();
			vote.setQuestionnaire(questionnaire);
			votes.add(vote);
		}
		List<Candidate> candidates = candidateService.findByQuestionnaireIdIn(ids);
		for (Candidate candidate : candidates) {
			for (Vote v : votes) {
				List<Candidate> vcandidates = v.getCandidates();
				if (vcandidates == null) {
					vcandidates = new ArrayList<Candidate>();
					v.setCandidates(vcandidates);
				}
				if (candidate.getQuestionnaireId() == v.getId()) {
					vcandidates.add(candidate);
					break;
				}
			}
		}
		HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/myvotes");
		return new ResponseEntity<>(votes, headers, HttpStatus.OK);
	}

	@GetMapping("/votes/{id}")
	@Timed
	public ResponseEntity<Vote> getVote(@PathVariable Long id) {
		log.debug("REST request to get Questionnaire : {}", id);
		Questionnaire questionnaire = questionnaireService.findOne(id);
		Vote vote = new Vote();
		vote.setId(questionnaire.getId());
		List<Candidate> candidates = candidateService.findByQuestionnaireId(questionnaire.getId());
		vote.setQuestionnaire(questionnaire);
		vote.setCandidates(candidates);
		return new ResponseEntity<>(vote, HttpStatus.OK);
	}

	@DeleteMapping("/votes/{id}")
	@Timed
	public ResponseEntity<Void> deleteQuestionnaire(@PathVariable Long id) {
		log.debug("REST request to delete Questionnaire : {}", id);
		questionnaireService.delete(id);
		candidateService.deleteByQuestionnaireId(id);
		return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("questionnaire", id.toString()))
				.build();
	}
}
